package com.heima.comment.service.Impl;

import com.heima.apis.user.SelectUser;
import com.heima.comment.service.CommentRepayService;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.constants.CommentConstants;
import com.heima.model.comment.dtos.CommentRepayDto;
import com.heima.model.comment.dtos.CommentRepayLikeDto;
import com.heima.model.comment.dtos.CommentRepaySaveDto;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class CommentRepayServiceImpl implements CommentRepayService {

    @Autowired
    private GreenTextScan textScan;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private SelectUser iUserClient;
    /**
     * 保存评论回复
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult save(CommentRepaySaveDto dto, HttpServletRequest request) {
        //校验参数
        if (StringUtils.isEmpty(dto)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //评论表回复对象
        ApCommentRepay apCommentRepay = new ApCommentRepay();

        //评论内容不能超过140个字
        if (dto.getContent().length() > 140) {
            return ResponseResult.errorResult(501, "评论字数过多");
        }
        //敏感词扫描
        Boolean scanComment = scanComment(dto.getContent());
        if (!scanComment) {
            return ResponseResult.errorResult(512, "评论检测不通过");
        }

        //存入评论表
        //通过feign接口根据用户id拿到用户名字
        String userId = request.getHeader("userId");
        ApUser apUser = iUserClient.selectUser(Integer.parseInt(userId));

        apCommentRepay.setAuthorName(apUser.getName());
        apCommentRepay.setAuthorId(Integer.parseInt(userId));

       /* apCommentRepay.setAuthorId(4);
        apCommentRepay.setAuthorName("admin");*/
        apCommentRepay.setCommentId(dto.getCommentId());
        apCommentRepay.setContent(dto.getContent());
        apCommentRepay.setLikes(0);
        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setUpdatedTime(new Date());

        mongoTemplate.save(apCommentRepay);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 点赞评论回复
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(CommentRepayLikeDto dto) {
        //校验参数
        if(StringUtils.isEmpty(dto)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //根据评论回复id查找回复表信息
        String commentRepayId = dto.getCommentRepayId();
        ApCommentRepay apCommentRepay = mongoTemplate.findById(commentRepayId, ApCommentRepay.class);

        if (dto.getOperation() == CommentConstants.LIKE) {
            apCommentRepay.setLikes(apCommentRepay.getLikes() + 1);
            apCommentRepay.setOperation((short)0);
            mongoTemplate.save(apCommentRepay);
        } else if (dto.getOperation() == CommentConstants.NOT_LIKE) {
            apCommentRepay.setLikes(apCommentRepay.getLikes() - 1);
            apCommentRepay.setOperation(null);
            mongoTemplate.save(apCommentRepay);
        }
        return ResponseResult.okResult(apCommentRepay);
    }

    /**
     * 分页展示回复
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(CommentRepayDto dto) {
        //校验参数
        if (StringUtils.isEmpty(dto)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //校验分页参数
        dto.checkParam();

        Date minDate = dto.getMinDate();
        //Date minDate = new Date(1640966400000L);

        Query query = Query.query(Criteria.where("commentId").is(dto.getCommentId())
                        .and("createdTime").lt(minDate))
                        .limit(dto.getSize()).with(Sort.by(Sort.Direction.DESC, "createdTime"));
        List<ApCommentRepay> apCommentRepays = mongoTemplate.find(query, ApCommentRepay.class);

        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), apCommentRepays.size());
        result.setData(apCommentRepays);

        return result;
    }

    private Boolean scanComment(String content) {
        boolean flag = true;
        try {
            Map map = textScan.greeTextScan(content);
            String suggestion = map.get("suggestion") + "";
            if ("block".equals(suggestion)) {
                flag = false;
            } else if ("review".equals(suggestion)) {
                flag = false;
            }
        } catch (Exception e) {
            log.error("文本扫描异常", e);
        }
        return flag;
    }
}
